<!-- 管理考生 -->
<template>
  <div v-loading="loading">
    <div class="config-step">
      <px-button type="primary" :icon="ArrowLeft" class="back-btn" @click="goBack">返回</px-button>
      <div class="step-form">
        <div class="table-top">
          <div>
            <span>考生人数：</span>
            <span>合计</span>
            <span>{{ tableData.length }}</span>
            <span>人</span>
          </div>
          <div>
            <px-button @click="handleBatchDelete">删除</px-button>
            <px-button type="primary" @click="handleAddStudent">添加</px-button>
          </div>
        </div>
        <px-table height="calc(100vh - 420px)" :data="tableData" size="small" border class="common-table" @selection-change="step2TableSelect">
          <px-table-column type="selection" fixed width="55" prop="selection" align="center" />
          <px-table-column prop="realName" label="姓名" min-width="120" show-overflow-tooltip />
          <px-table-column prop="empNo" label="工号" min-width="120" show-overflow-tooltip />
          <px-table-column prop="deptName" label="组织" min-width="120" show-overflow-tooltip />
          <px-table-column prop="phone" label="手机号码" min-width="120" show-overflow-tooltip />
          <px-table-column prop="planTime" label="考试计划时间" min-width="120" show-overflow-tooltip />
          <px-table-column prop="createTime" label="添加时间" min-width="100" show-overflow-tooltip />
          <px-table-column label="操作" width="120" fixed="right" align="center">
            <template #header>
              <div class="cell-title">
                <span class="text">操作</span>
                <px-tooltip effect="dark" content="考试次数用尽，点击重置次数按钮将考生考试次数重置为0并清空考试记录" placement="top">
                  <px-icon v-if="handleType == 'Edit'"><WarningFilled /></px-icon>
                </px-tooltip>
              </div>
            </template>
            <template #default="scope">
              <px-tooltip content="修改计划" placement="top">
                <px-button link icon="EditPen" type="danger" @click="handleEditPlan(scope)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button link icon="Delete" type="danger" @click="handleDeleteStudent(scope.$index)" />
              </px-tooltip>
              <px-tooltip content="重置次数" placement="top">
                <px-button v-if="handleType == 'Edit'" link icon="Tools" type="danger" @click="handleResetStudent(scope)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <div class="step-footer">
          <px-button @click="cancel">取消</px-button>
          <px-button type="primary" @click="toStep3">保存</px-button>
        </div>
        <div v-if="addStudentVisible">
          <AddStudent v-model:visible="addStudentVisible" @add="confirmAddStudent" />
        </div>
        <px-dialog v-model="editPlanVisible" title="修改考试计划时间" width="650">
          <px-form ref="editPlanFormRef" :model="editPlanForm">
            <px-form-item label="考试计划时间" prop="time" label-width="150">
              <px-date-picker
                v-model="editPlanForm.time"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :disabled-date="disabledDate"
              />
            </px-form-item>
          </px-form>
          <template #footer>
            <span class="dialog-footer">
              <px-button @click="() => (editPlanVisible = false)">取消</px-button>
              <px-button type="primary" @click="saveBtn">确定</px-button>
            </span>
          </template>
        </px-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, toRefs } from "vue";
import { getExamConfigAPI, saveExamineeAPI, resetExamTimesAPI } from "@/api/knowledge/examManage";
import { ArrowLeft } from "@px-ui/icons-vue";
import { PxMessage, PxMessageBox } from "px-ui";
import AddStudent from "./addStudent.vue";
import dayjs from "dayjs";

const props = defineProps({
  handleType: {
    type: String,
    default: "Add"
  },
  rowData: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(["goBack"]);

const state = reactive({
  loading: false,
  baseForm: {
    name: "",
    type: null,
    className: "",
    count: null,
    totalScore: null,
    passScore: null,
    period: null,
    intruction: "",
    attention: ""
  },
  tableData: [],
  addStudentVisible: false,
  editPlanVisible: false,
  editPlanForm: {
    time: ""
  },
  tableSelectedData: [],
  editData: {},
  subjectTableData: [],
  data_back: [],
  subjectTableSelectedData: []
});
const { loading, tableData, addStudentVisible, editPlanVisible, editPlanForm } = toRefs(state);

onMounted(() => {
  if (props.handleType === "Edit") {
    editSearch();
  }
});

const disabledDate = time => {
  // 禁用早于今天的日期（不含今天）
  return dayjs(time).isBefore(dayjs(), "day");
};

const handleBatchDelete = () => {
  if (state.tableSelectedData.length === 0) {
    PxMessage.error("请选择要删除的数据");
    return;
  }
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const a1 = state.tableData;
      const a2 = state.tableSelectedData;
      state.tableData = a1.filter(row => !a2.includes(row));
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const goBack = () => {
  emits("goBack");
};

const cancel = () => {
  goBack();
};

const toStep3 = () => {
  handleSubmit();
};

const handleAddStudent = () => {
  state.addStudentVisible = true;
};

const confirmAddStudent = data => {
  data?.data?.map(item => {
    if (state.tableData.filter(v => v.empNo === item.empNo).length === 0) {
      let time = data?.time;
      item.planStartTime = time[0];
      item.planEndTime = time[1];
      let startTime = time[0].split(" ")[0] ?? "";
      let endTime = time[1].split(" ")[0] ?? "";
      item.planTime = startTime + "至" + endTime;
      state.tableData.push(item);
    }
  });
  state.addStudentVisible = false;
};

const step2TableSelect = val => {
  state.tableSelectedData = val;
};

const handleEditPlan = val => {
  const row = val?.row;
  let planStartTime = row?.planStartTime ?? "";
  let planEndTime = row?.planEndTime ?? "";
  state.editPlanForm.time = [planStartTime, planEndTime];
  state.editPlanForm.index = val?.$index;
  state.editPlanVisible = true;
};

// 修改考试计划时间保存
const saveBtn = () => {
  let { index, time } = state.editPlanForm;
  let startTime = time[0].split(" ")[0] ?? "";
  let endTime = time[1].split(" ")[0] ?? "";
  state.tableData[index].planStartTime = time[0];
  state.tableData[index].planEndTime = time[1].split(" ")[0] + " 23:59:59";
  state.tableData[index].planTime = startTime + "至" + endTime;
  state.editPlanVisible = false;
};

const handleDeleteStudent = index => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      state.tableData.splice(index, 1);
      PxMessage.success("删除成功");
    })
    .catch(() => {});
};

const handleResetStudent = item => {
  let data = item;
  let rowData = props?.rowData || {};
  PxMessageBox.confirm("是否重置该考生的考试次数、清空考试记录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params = {
        examId: rowData?.examId || "",
        examineeId: data?.row?.userId || ""
      };
      await resetExamTimesAPI(params);
      PxMessage.success("重置成功");
    })
    .catch(() => {});
};

const editSearch = async () => {
  try {
    state.loading = true;
    const params = {
      examId: props.rowData.examId
    };
    const res = await getExamConfigAPI(params);
    state.editData = res;
    const base = res?.examineBase;
    state.baseForm = {
      name: base?.examName ?? "",
      type: base?.examCategoryId ?? "",
      className: base?.department ?? "",
      count: base?.examTimes,
      totalScore: base?.totalScore ?? "",
      passScore: base?.passScore ?? "",
      period: base?.duration ?? "",
      intruction: base?.intro ?? "",
      attention: base?.notice ?? ""
    };
    state.tableData = res.examinees.map(v => {
      return {
        realName: v?.examineeName ?? "",
        empNo: v?.workNo ?? "",
        deptName: v?.org ?? "",
        phone: v?.mobile ?? "",
        userId: v?.examineeId ?? "",
        createTime: v?.createTime ?? "",
        planStartTime: v?.planStartTime ?? "",
        planEndTime: v?.planEndTime ?? "",
        planTime: v?.planStartTime?.split(" ")[0] + "-" + v?.planEndTime?.split(" ")[0]
      };
    });
    state.subjectTableData = res.questions.map(v => {
      return {
        questionName: v?.questionName ?? "",
        typeName: v?.questionTypeName ?? "",
        score: v?.score ?? "",
        updateTime: v?.updateTime ?? "",
        updateByName: v?.updateByName ?? "",
        categoryId: v?.categoryId ?? "",
        questionId: v?.questionId ?? "",
        type: v?.questionType ?? "",
        answer: v?.answer ?? ""
      };
    });
    state.data_back = state.subjectTableData;
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};

const save = async () => {
  const params = {
    examId: props.handleType === "Add" ? null : props.rowData.examId,
    examineBase: {
      examId: props.handleType === "Add" ? null : props.rowData.examId,
      examName: state.baseForm.name,
      // categoryId: state.baseForm.type,
      examCategoryId: state.baseForm.type,
      department: state.baseForm.className,
      examTimes: state.baseForm.count,
      totalScore: state.baseForm.totalScore,
      passScore: state.baseForm.passScore,
      duration: state.baseForm.period,
      intro: state.baseForm.intruction,
      notice: state.baseForm.attention
    },
    examinees: state.tableData.map(item => {
      return {
        examId: props.handleType === "Add" ? null : props.rowData.examId,
        examineeName: item.realName,
        workNo: item.empNo,
        org: item.deptName,
        mobile: item.phone,
        examineeId: item.userId,
        planStartTime: item.planStartTime,
        planEndTime: item.planEndTime
      };
    }),
    questions: state.subjectTableData.map((item, index) => {
      return {
        categoryId: item.categoryId,
        questionId: item.questionId,
        questionName: item.questionName,
        questionType: item.type,
        sort: index,
        score: item.score,
        answer: item.answer,
        assembleWay: "",
        updateByName: item.updateByName,
        updateTime: item.updateTime,
        // categoryName: "",
        questionTypeName: item.typeName,
        examid: props.handleType === "Add" ? null : props.rowData.examId
      };
    })
  };
  try {
    state.loading = true;
    await saveExamineeAPI(params);
    goBack();
    PxMessage.success(`${props.handleType === "Add" ? "新增" : "编辑"}成功`);
  } catch (err) {
    console.log(err);
  } finally {
    state.loading = false;
  }
};
const handleSubmit = async () => {
  if (!state.tableData?.length) {
    PxMessage.error("请添加考生");
    return;
  }
  save();
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/knowledge/examManage/scss/common.scss");

.config-step {
  position: relative;
  width: 100%;

  .back-btn {
    position: absolute;
    left: 0;
  }

  .step-container {
    width: 400px;
    margin: 0 auto;
  }

  .step-form {
    position: relative;
    width: 80%;
    height: calc(100vh - 240px);
    padding: 40px 0 20px;
    margin: 0 auto;
  }

  .step-footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    text-align: center;
  }
}

.table-top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.preview-content {
  width: 100%;
  height: calc(100vh - 450px);
}

.topic-info-title {
  font-size: 16px;
  font-weight: bold;

  .topic-info {
    margin-right: 32px;
  }
}

.over-score {
  color: #ef4444;
}

.cell-title {
  display: flex;
  align-items: center;
  justify-content: center;

  .px-icon {
    color: rgb(59 130 246);
  }
}
</style>
